package com.study.service.hystrix;

import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.netflix.hystrix.HystrixRequestCache;
import com.netflix.hystrix.strategy.concurrency.HystrixConcurrencyStrategyDefault;
import com.study.service.NacosClientService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.ServiceInstance;

import java.util.Collections;
import java.util.List;

/**
 * 带有缓存功能的hystrix
 */

@Slf4j
public class CacheHystrixCommand extends HystrixCommand<List<ServiceInstance>> {

    //需要保护的服务
    private final NacosClientService nacosClientService;

    //方法需要传递的参数
    private final String serviceId;

    private static final HystrixCommandKey CACHE_KEY =
            HystrixCommandKey.Factory.asKey("CacheHystrixCommand");

    public CacheHystrixCommand(NacosClientService nacosClientService,
                                String serviceId){

        super(
                HystrixCommand.Setter
                    .withGroupKey(HystrixCommandGroupKey
                            .Factory.asKey("CacheHystrixCommand"))
                .andCommandKey(CACHE_KEY)
        );

        this.nacosClientService = nacosClientService;
        this.serviceId = serviceId;
    }


    @Override
    protected List<ServiceInstance> run() throws Exception {

        log.info("CacheHystrixCommand in hystrix command to get service instance" +
                "[{}],[{}]", this.serviceId,Thread.currentThread().getName());

        return this.nacosClientService.getNacosClientInfo(this.serviceId);
    }

    @Override
    protected String getCacheKey() {
        return super.getCacheKey();
    }

    @Override
    protected List<ServiceInstance> getFallback() {
        return Collections.emptyList();
    }

    /**
     * 根据缓存 key 清理在一次 hystrix 请求上下文中的缓存
     * @param serviceId
     */
    public static void flushRequestCache(String serviceId){

        HystrixRequestCache.getInstance(
                CACHE_KEY, HystrixConcurrencyStrategyDefault.getInstance()
        ).clear(serviceId);
        log.info("flush request cache in hystrix command: [{}],[{}]"
                , serviceId,Thread.currentThread().getName());

    }
}
